<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

$THEME->addBreadcrumb($this->adminUrl.'/workspaces/copy', $this->lang('ap_title_workspaces_copy'));

JFX::checkAdminPermsRedirect('core', 'perm_publish_workspaces');


$fromId = (int) get('from');
$toId = (int) get('to');

$workspaces = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}workspaces ORDER BY title ASC");
$wsOpts = array('0' => 'Select a Workspace');
foreach($workspaces as $k=>$v){
    $wsOpts[$v['id']] = $v['title'];
};

$wsSelect = '<select id="jfx-workspace-select-from">';
foreach($wsOpts as $k=>$v){
    if($k==$fromId) $selected = 'selected="selected"';
    else $selected = '';
    $wsSelect .= '<option value="'.$k.'" '.$selected.'>From: '.$v.'</option>';
}
$wsSelect .= '</select>';



$wsOpts2 = array('0' => 'Select a Workspace');
foreach($workspaces as $k=>$v){
    $wsOpts2[$v['id']] = $v['title'];
};

$wsSelect2 = '<select id="jfx-workspace-select-to">';
foreach($wsOpts2 as $k=>$v){
    if($k==$toId) $selected = 'selected="selected"';
    else $selected = '';
    $wsSelect2 .= '<option value="'.$k.'" '.$selected.'>To: '.$v.'</option>';
}
$wsSelect2 .= '</select>';

echo $wsSelect.$wsSelect2;

echo '<div class="jfx-clear"></div>';



$VIEW->addJs('
$(document).ready(function(){
    $("#jfx-workspace-select-to").change(function(){
        window.location = "'.$CONFIG->adminUrl.'/workspaces/copy?from='.$fromId.'&to="+this.options[this.selectedIndex].value;
    });
    $("#jfx-workspace-select-from").change(function(){
        window.location = "'.$CONFIG->adminUrl.'/workspaces/copy?to='.$toId.'&from="+this.options[this.selectedIndex].value;
    });
});
');


$js = '
$(document).ready(function(){
    $("#jfxcore-copy-workspace-tree-from, #jfxcore-copy-workspace-tree-to").treeview({
        persist: "location",
        collapsed: true,
        unique: true
    });
    $("#jfxcore-copy-workspace-tree-from a").click(function(){
        $("#jfx-parent-id-from").get(0).value = this.id.replace("jfx-page_from_", "");
        $("#jfx-disabled-parent-from").get(0).value = $(this).text();
    });
    $("#jfxcore-copy-workspace-tree-to a").click(function(){
        $("#jfx-parent-id-to").get(0).value = this.id.replace("jfx-page_to_", "");
        $("#jfx-disabled-parent-to").get(0).value = $(this).text();
    });
});
';
$VIEW->addJs($js);


if(get('from')=='' || get('to')==''){
    // need to select their workspaces







}else{
    // have selected their workspaces

$fromId = (int) get('from');
$toId = (int) get('to');

if($DB->countRows($CONFIG->dbprefix.'workspaces', "id = '{$fromId}'")==0){
    JFX::redirect($CONFIG->adminUrl.'/workspaces/copy/?to='.$toId);
}
if($DB->countRows($CONFIG->dbprefix.'workspaces', "id = '{$toId}'")==0){
    JFX::redirect($CONFIG->adminUrl.'/workspaces/copy/?from='.$fromId);
}

// have valid workspaces


if(Antz_IntelliForm::submitted('copy-workspace')){
    $error = false;

    $fromPageId = (int) post('parentFrom');
    $toPageId = (int) post('parentTo');

    if($fromPageId == 0 || $toPageId == 0){
        $error = false;
    }else{
        if($DB->countRows($CONFIG->dbprefix.'pages', "id = '{$fromPageId}' AND workspace_id = '{$fromId}'")==0){
            $error = true;
            JFX::addError('The page to copy from cannot be found in this workspace');
        }
        if($DB->countRows($CONFIG->dbprefix.'pages', "id = '{$toPageId}' AND workspace_id = '{$toId}'")==0){
            $error = true;
            JFX::addError('The page to copy to cannot be found in this workspace');
        }
    }

    if($fromPageId == $toPageId){
        JFX::addError('Source and destination are identical!');
        $error = true;
    }

    // check that they arent moving the page into a subpage of itself
    $toParentIds = array();
    JFX::getParentIdsAsArray($toPageId, $toParentIds);
    if(in_array($fromPageId, $toParentIds)){
        $error = true;
        JFX::addError('Impossible to move a page into a subpage of itself!');
    }

    if(!$error){
        // defined in external file to keep this one tidy
        $deleteDeadPages = (bool) post('deleteDeadPages');
        include('copy/do-copy.php');
        JFX::addSuccess('Copied successfully!');
        //JFX::redirect(THIS_PAGE_URL);
    }   
}



$pagesRecursiveFrom = JFX::getPageTree(0, $fromId);

$treeFrom = '<ul id="jfxcore-copy-workspace-tree-from">'.JFX_CopyWorkspaces_MakeTree($pagesRecursiveFrom, 'jfx-page_from_', $fromId).'</ul>';

$pagesRecursiveTo = JFX::getPageTree(0, $toId);

$treeTo = '<ul id="jfxcore-copy-workspace-tree-to">'.JFX_CopyWorkspaces_MakeTree($pagesRecursiveTo, 'jfx-page_to_', $toId).'</ul>';



$parentTitleTo = 'Root';
$parentTitleFrom = 'Root';

    $parentFrom = array(
        'name' => 'parentFrom',
        'value' => post('parentFrom', 0),
        'type' => 'hidden',
        'id' => 'jfx-parent-id-from',
        'label' => ''
    );
    $parentListFrom = array(
        'type' => 'longtag',
        'tag' => 'div',
        'class' => 'form-field',
        'id' => 'jfx-parent-page-tree-from',
        'content' => '<label>Page to be copied<br />
(From '.$DB->oneValue($CONFIG->dbprefix.'workspaces', 'title', "id = '{$fromId}'").')</label>
<div class="input-area">'.$treeFrom.'</div>'
    );
    $selectedParentFrom = array(
        'name' => 'disabled_parent_from',
        'value' => post('disabled_parent_from', $parentTitleFrom),
        'type' => 'text',
        'id' => 'jfx-disabled-parent-from',
        'extra' => array(
            array(
                'command' => 'addAttribute',
                'params' => array(
                    '"disabled"', '"disabled"'
                )
            )
        ),
        'label' => '&nbsp;'
    );


    $parentTo = array(
        'name' => 'parentTo',
        'value' => post('parentTo', 0),
        'type' => 'hidden',
        'id' => 'jfx-parent-id-to',
        'label' => ''
    );
    $parentListTo = array(
        'type' => 'longtag',
        'tag' => 'div',
        'class' => 'form-field',
        'id' => 'jfx-parent-page-tree-to',
        'content' => '<label>Page to copy <u>INTO</u><br />
(To '.$DB->oneValue($CONFIG->dbprefix.'workspaces', 'title', "id = '{$toId}'").')</label>
<div class="input-area">'.$treeTo.'</div>'
    );
    $selectedParentTo = array(
        'name' => 'disabled_parent_to',
        'value' => post('disabled_parent_to', $parentTitleTo),
        'type' => 'text',
        'id' => 'jfx-disabled-parent-to',
        'extra' => array(
            array(
                'command' => 'addAttribute',
                'params' => array(
                    '"disabled"', '"disabled"'
                )
            )
        ),
        'label' => '&nbsp;'
    );


$formFields = array(
    $parentFrom,
    $parentListFrom,
    $selectedParentFrom,
    $parentTo,
    $parentListTo,
    $selectedParentTo,
    array(
        'type' => 'checkbox',
            'value' => '1',
            'name' => 'deleteDeadPages',
            'label' => 'Delete Dead Pages?',
            'checked' => post('deleteDeadPages', 0)
    ),
    array(
        'type' => 'submit',
            'name' => 'submitBtn',
            'value' => 'Copy!',
            'label' => '&nbsp;'
    )
);

echo JFX::makeRapidForm($formFields, 'Select Pages To Copy', 'copy-workspace');


}







function JFX_CopyWorkspaces_MakeTree($arr, $idPrefix='page_', $workspaceid){
    $CONFIG = JFX::registry('config');
    $LANG = JFX::registry('lang');
    $returnString = '';
    foreach($arr as $k=>$v){

        $link = '<a href="javascript: void(null)" id="'.$idPrefix.$v['id'].'">'.$LANG->getContent('core', 'page_title', $v['id'], '', $workspaceid).'</a>';
        if(isset($v['subpages']) && count($v['subpages'])>0){
            $subpages = '<ul>'.JFX_CopyWorkspaces_MakeTree($v['subpages'], $idPrefix, $workspaceid).'</ul>';
        }else{
            $subpages = '';
        }
        $returnString .= '<li>'.$link.$subpages.'</li>';
    }

    return $returnString;
}


